package cn.vendcommon.com.utils;

import cn.vendcommon.com.entity.MistakeMessage;
import cn.vendcommon.com.entity.constants.MistakeConstants;
import cn.vendcommon.com.entity.interfaces.MistakeCategory;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 错误信息聚合工具类
 */
public class MistakeAggregatorUtil {

    /**
     * 合并任意列表，返回去重后的 MistakeMessage 列表（按 createTime 降序）
     */
    public static List<MistakeMessage> aggregateLists(List<?>... lists) {
        List<MistakeMessage> mistakeMessageList = new ArrayList<>();
        for (List<?> list : lists) {
            if(list == null || list.isEmpty()) continue;
            for(Object o : list) {
                MistakeMessage mm = buildMessageFromObject(o);
                if(mm != null) mistakeMessageList.add(mm);
            }
        }
        return mistakeMessageList;
    }

    /**
     * 从任意对象构建 MistakeMessage
     * @param obj
     * @return
     */
    private static MistakeMessage buildMessageFromObject(Object obj) {
        if (obj == null) return null;
        MistakeMessage mm = new MistakeMessage();
        String type = obj.getClass().getAnnotation(MistakeCategory.class).value();
        if (type.equals(MistakeConstants.SYSTEM_MISTAKE)) {
            mm.setDisplayType(prettifyClassName(obj.getClass().getSimpleName()));
        } else if (type.equals(MistakeConstants.YOLO_RECOGNITION_LOG)) {
            mm.setDisplayType(prettifyClassName(obj.getClass().getSimpleName()));
        }
        mm.setData(obj);
        return mm;
    }

    /**
     * 美化类名，例如 "YoloRecognitionLog" -> "Yolo Recognition Log"
     */
    private static String prettifyClassName(String className) {
        StringBuilder sb = new StringBuilder();
        for (char c : className.toCharArray()) {
            if (!sb.isEmpty() && Character.isUpperCase(c) && sb.charAt(sb.length()-1) != ' ') {
                sb.append(' ');
            }
            sb.append(c);
        }
        return sb.toString();
    }
}
